package com.nd.android.u.ui.activity.recent_contact;

import ims.manager.IMSStateManager;
import ims.outInterface.IStateObserver;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.common.StarAppCIConst;
import com.common.StarAppConst;
import com.common.allCommon.AllCommonUtils;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.common.widget.view.CommonPopup;
import com.common.widget.view.CommonPopup.IOnOper;
import com.nd.android.u.business.db.dao.RecentContactRecords;
import com.nd.android.u.commonWidget.NotificationMsg;
import com.nd.android.u.controller.ChatConst;
import com.nd.android.u.controller.ChatConst.KEY;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.MessageConst.ChatNotify;
import com.nd.android.u.controller.bean.contact.ForwardingParam;
import com.nd.android.u.controller.bean.event.MessageReceivedEvent;
import com.nd.android.u.controller.bean.event.UnreadCountChangedEvent;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IMessageObserver;
import com.nd.android.u.controller.observer.MessageDispatcher;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.addGroupMember.adapter.AddFriendOrGroupAdapter;
import com.product.android.business.switchUser.SwitchUserReloadManager.TabIdentifier;
import com.product.android.business.switchUser.TabUIRefresh;
import com.product.android.ui.activity.BaseFragmentActivity;

import de.greenrobot.event.EventBus;

public class RecentContactRecordActivity extends BaseFragmentActivity implements
		IStateObserver, TabUIRefresh {

	public static final String CLICK_FLAG = "click_flag";
	private static final int CLICK_DEFAULT_VALUE = 0;
	public static final int CLICK_AGAIN_VALUE = 1;

	public static final String RECENT_CONTACT_CLOSE_SEARCH_UI = "recent_contact_close_search_ui";
	public static final String RECENT_CONTACT_UPDATE_UI = "recent_contact_update_ui";

	private static final String RECEIVE_MSG = "receive_msg";
	private static final String UPDATE_TITLE = "update_title";
	public static final String MSG_UPDATE = "msg_update";

	private static final int CONTENT_CONTAINER_ID = R.id.content_container;
	private static final String NO_CONTACT_RECORD = "no_contact_record";
	private static final String CONTACT_RECORD_LIST = "contact_record_list";
//	private static final String SEARCH_RECORD_LIST = "search_contacts_list";

	private static final Map<ContentType, String> TYPE_2_TAG = new HashMap<ContentType, String>();
	static {
		TYPE_2_TAG.put(ContentType.NO_CONTACT_RECORD, NO_CONTACT_RECORD);
		TYPE_2_TAG.put(ContentType.CONTACT_RECORD_LIST, CONTACT_RECORD_LIST);
	}

	public static ForwardingParam mForwardingParam; // 存放转发消息的参数，值为null表示不是用于转发的情况

	private CommonActivityTitle mTvTitle;

	private ContentType mCurrentContentType; // 存储当前内容区类型

	private ProcessState mCurNetworkState; // 存储表示网络状态的信息
	
	/** 用于确定弹出框位置的view，不会显示 */
	private View mvewPopupAnchor;
	private RecentContactListFragment mContactListFragment;
	/** 发起群聊/添加朋友弹出框 */
	private CommonPopup mPopup = null;

	private static enum ProcessState {
		ADD, REMOVE;
	}

	private static enum ContentType {
		NO_CONTACT_RECORD, CONTACT_RECORD_LIST
	}

	@Override
	protected boolean _onCreate(Bundle savedInstanceState) {
		if (super._onCreate(savedInstanceState)) {
			setContentView(R.layout.recent_contact_record);
			mTvTitle =(CommonActivityTitle) findViewById(R.id.common_chat_title);
			mTvTitle.setTitleTextTypeface(StarAppConst.getInstance().getLTXTypeface(), false);
			
			mvewPopupAnchor = (View) findViewById(R.id.view_popup_anchor);
			mTvTitle.setTitleBtnCallback(mTitleBtnCallBack);

			EventBus.getDefault().register(this, UnreadCountChangedEvent.class);
			EventBus.getDefault().register(this, String.class);
			EventBus.getDefault().register(this, MessageReceivedEvent.class);
			
			return true;
		} else {
			return false;
		}
	}

	public boolean isNormalUse() {
		return (mForwardingParam == null);
	}

	private void setTitleText() {
		StringBuilder sb = new StringBuilder();
		if (isNormalUse()) {
            mTvTitle.hideLeftBtn();
            mTvTitle.setLeftBtnEnabel(false);
            mTvTitle.showRightBtn();
            mTvTitle.setRightBtnEnabel(true);
			sb.append(getString(R.string.str_friend));

			int state = IMSStateManager.getInstance().getConnectState(); // 连接状态
			if (state == IMSStateManager.CONNECT_STATE_ONLINE) {
				int unReadMsgCounts = RecentContactRecords.INSTANCE
						.getAllUnreadMsgCount();
				if (unReadMsgCounts > 0) {
					sb.append('(');
					sb.append(unReadMsgCounts);
					sb.append(')');
				}
			} else if (state == IMSStateManager.CONNECT_STATE_OFFLINE) {
				sb.append(getString(R.string.offline));
			} else if (state == IMSStateManager.CONNECT_STATE_LOGINING) {
				sb.append(getString(R.string.connecting));
			}
		} else {
			sb.append(getString(R.string.choosefriend));
            mTvTitle.showLeftBtn();
            mTvTitle.setLeftBtnEnabel(true);
            mTvTitle.hideRightBtn();
            mTvTitle.setRightBtnEnabel(false);
		}
		mTvTitle.setTitleText(sb.toString());
	}

	/**
	 * 
	 * @n<b>函数名称</b>     :processOfflineTip
	 * @brief                网络可用,不可用提示条的添加或删除
	 * @see
	 * @since    Ver 1.1
	 * @param  @param ps
	 * @param  @param retrycount
	 * @return void
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-4-16上午10:34:07
	 */
	private void processOfflineTip(ProcessState ps, final int retrycount) {
		int containerId = R.id.offline_container;
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		Fragment fragment = fm.findFragmentById(containerId);

		if (ps == ProcessState.ADD) {
			if (fragment == null) {
				Fragment newFragment = OfflineFragment.newInstance();
				ft.add(containerId, newFragment);
				ft.commitAllowingStateLoss();
				mCurNetworkState = ps;
			}
		} else if (ps == ProcessState.REMOVE) {
			if (fragment != null) {
				ft.remove(fragment);
				ft.commitAllowingStateLoss();
				mCurNetworkState = ps;
			} else if (ProcessState.ADD == mCurNetworkState) {
				if (retrycount > 20) {
					return;
				}
				mTvTitle.postDelayed(new Runnable() { // 防止出现某些情况下网络切换后表示网络状态的fragment显示不正确的问题

							@Override
							public void run() {
								processOfflineTip(ProcessState.REMOVE,
										retrycount + 1);
							}
						}, 100);
			}
		}
	}

	//根据tag返回Fragment
	private Fragment tag2Frament(String tag) {
		if (tag.equals(NO_CONTACT_RECORD)) {
			return NoContactRecordFragment.newInstance();
		} else if (tag.equals(CONTACT_RECORD_LIST)) {
			mContactListFragment = RecentContactListFragment.newInstance(mForwardingParam);
			return mContactListFragment;
		}
//		else if (tag.equals(SEARCH_RECORD_LIST)) {
//			return RecentContactSearchFragment.newInstance(mForwardingParam);
//		}
		else {
			return null;
		}
	}

	// 根据情况添加内容区界面
	private void addContentFragment() {
		ContentType addType;

		if (RecentContactRecords.INSTANCE.isEmpty()) {
			addType = ContentType.NO_CONTACT_RECORD;
		} else {
			addType = ContentType.CONTACT_RECORD_LIST;
		}

		FragmentManager fm = getSupportFragmentManager();
		if (mCurrentContentType == null) { // 内容区尚未添加过任何一个界面
			FragmentTransaction ft = fm.beginTransaction();
			Fragment newFragment = tag2Frament(TYPE_2_TAG.get(addType));
			ft.add(CONTENT_CONTAINER_ID, newFragment);
			ft.commitAllowingStateLoss();
			mCurrentContentType = addType;
		} else { // 内容区已有界面
			if (mCurrentContentType == addType) {
				return; // 类型一样，不用处理了
			} else {
				FragmentTransaction ft = fm.beginTransaction();
				Fragment newFragment = tag2Frament(TYPE_2_TAG.get(addType));
				ft.replace(CONTENT_CONTAINER_ID, newFragment);
				ft.commitAllowingStateLoss();
				mCurrentContentType = addType;
			}
		}
	}

    @Override
    protected void onStart() {
        super.onStart();
        MessageDispatcher.getInstance().registAllObserver(LocalMessageType.class, mMsgObserver);
        MessageDispatcher.getInstance().registObserver(LocalMessageType.APP, mMsgObserver);
    }
	@Override
	public void onResume() {
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){				
			String generateId = bundle.getString(ChatConst.KEY.REPOST_DATA);
			if (!TextUtils.isEmpty(generateId)) {
				mForwardingParam = new ForwardingParam();
				mForwardingParam.mGenerateId = generateId;
				mForwardingParam.mMsgType = bundle
						.getInt(ChatConst.KEY.REPOST_TYPE);
				if (bundle.containsKey(ChatConst.KEY.REPOST_FID)) {
					mForwardingParam.mId = bundle.getLong(ChatConst.KEY.REPOST_FID);
				} else if (bundle.containsKey(ChatConst.KEY.REPOST_GID)) {
					mForwardingParam.mId = bundle.getLong(ChatConst.KEY.REPOST_GID);
				}
			}else{
				mForwardingParam = null;
			}
		}else{
			mForwardingParam = null;
		}
		
		setTitleText();
		IMSStateManager instance = IMSStateManager.getInstance();
		if (instance.isNetworkAvailable()) {
			processOfflineTip(ProcessState.REMOVE, 0);
		} else {
			processOfflineTip(ProcessState.ADD, 0);
		}
		addContentFragment();
		
		instance.registStateObserver(this); // 注册观察连线状态

		super.onResume();

		// 检查是否刚切换完身份或帐号需要重新刷新界面，需要的话重新加载数据、进行刷新并重置刷新标志位
		AllCommonUtils.tabActivityCheckUserSwitch(this, this);
	}

	@Override
	protected void onPause() {
       
		IMSStateManager.getInstance().unrigestStateObserver(this);
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
	    MessageDispatcher.getInstance().unregistAllObserver(LocalMessageType.class, mMsgObserver);
        MessageDispatcher.getInstance().unregistObserver(LocalMessageType.APP, mMsgObserver);
		EventBus.getDefault().unregister(this, UnreadCountChangedEvent.class);
		EventBus.getDefault().unregister(this, String.class);
		EventBus.getDefault().unregister(this, MessageReceivedEvent.class);
		super.onDestroy();
	}

	// @Override
	// public void onBackPressed() {
	// if (mSearchBar.isCancelLayoutVisible()) { // 搜索栏可见
	// mSearchBar.setSearchBarState(SearchBarWidget.LAYOUT_STATE_VIEW);
	// return;
	// }
	// super.onBackPressed();
	// }

	private IMessageObserver mMsgObserver = new IMessageObserver() {

        @Override
        public void onReceiveMessage(IMessageDisplay message) {
            EventBus.getDefault().post(new MessageReceivedEvent());
        }

        @Override
        public void onMessageStateChanged(IMessageDisplay message, int state) {
            EventBus.getDefault().post(new MessageReceivedEvent());
        }

        @Override
        public void onOtherMessageNotify(final Message message) {
        	if (message==null){
        		return;
        	}
        	
        	switch (message.what) {
			case StarAppCIConst.CHAT_NOTIFY_USER_NAME:
			case StarAppCIConst.CHAT_NOTIFY_GROUP_NAME_210003:
				final Bundle bundle=message.getData();
				if (bundle!=null && mContactListFragment!=null){
					runOnUiThread(new Runnable() {
						public void run() {
							long id;
							if (message.what==StarAppCIConst.CHAT_NOTIFY_USER_NAME){
								id=bundle.getLong(KEY.FID);
							}else{
								id=bundle.getLong(KEY.GID);
							}
							mContactListFragment.resetRecentContactName(id);		
						}
					});
				}
				break;
			case ChatNotify.GROUP_DEL:
				EventBus.getDefault().post(new UnreadCountChangedEvent());
				break;

			default:
				break;
			}
        }

        @Override
        public void onSendNewMessage(IMessageDisplay message) {
           
        }
		
	};

	public void onEventMainThread(String param) {
		if (TextUtils.isEmpty(param)) {
			return;
		}
		if (param.equals(RECEIVE_MSG)) {
			setTitleText();
			addContentFragment();
			EventBus.getDefault().post(MSG_UPDATE);
		} else if (param.equals(UPDATE_TITLE)) {
			setTitleText();
		} 
//		else if (param.equals(RECENT_CONTACT_CLOSE_SEARCH_UI)) {
//			mSearchBar.performClickCancel();
//			addContentFragment();
//		}
		else if (param.equals(RECENT_CONTACT_UPDATE_UI)) {
			addContentFragment();
		}
	}
	
	public void onEventMainThread(UnreadCountChangedEvent event) {
		setTitleText();
	}
	
    /**
     * 事件监听, 接收到新的消息
     * <br>Created 2014-8-7 下午3:13:36
     * @param e 事件对象
     * @author       yufeng
     */
    public void onEventMainThread(MessageReceivedEvent e) {
        e.receivedBy(this);
        
        setTitleText();
        addContentFragment();
        EventBus.getDefault().post(MSG_UPDATE);
    }
	
	
	@Override
	public void onConnectStateChanged(int connectState) {
		EventBus.getDefault().post(UPDATE_TITLE);
	}

	@Override
	public void onOnlineStateChanged(int onlineState) {
		EventBus.getDefault().post(UPDATE_TITLE);
	}

	public static class SearchParam {
		public String mSearchText;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (isNormalUse()) {
			menu.add(getResources().getString(R.string.all_readed));
		}
		return super.onCreateOptionsMenu(menu);
	}
//	
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		if (isNormalUse()) {
//			RecentContactRecords instance = RecentContactRecords.INSTANCE;
//			if (instance.getAllUnreadMsgCount() != 0) {
//				instance.clearAllUnreadFlag();
//				EventBus.getDefault().post(new UnreadCountChangedEvent());
//
//				// 向服务端确认所有未读消息
////				new Thread(new Runnable() {
////
////					@Override
////					public void run() {
////						// XXX 待确认  MessageAckHandler 目前91u中也没有此操作
////						MessageAckHandler.getInstance().ackAllUnReadMsg();
////					}
////				}).start();
//			}
//
//			// 清除通知栏消息
//			NotificationMsg.getInstance().callbackSetNotiType();
//		}
//		return super.onOptionsItemSelected(item);
//	}

	@Override
	public void onNetworkStateChanged(int networkState) {
		if (networkState == IMSStateManager.NETWORK_STATE_DISCONNECT) { // 没有连接到网络
			processOfflineTip(ProcessState.ADD, 0);
		} else if ((networkState == IMSStateManager.NETWORK_STATE_WIFI)
				|| (networkState == IMSStateManager.NETWORK_STATE_GPRS)) {
			processOfflineTip(ProcessState.REMOVE, 0);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		if (intent != null) {
			int value = intent.getIntExtra(CLICK_FLAG, CLICK_DEFAULT_VALUE);
			if (value == CLICK_AGAIN_VALUE) {
				EventBus.getDefault()
						.postSticky(
								RecentContactListFragment.RECENT_CONTACT_LIST_SET_NEXT_UNREAD_ITEM);
			}
		}
	}

	@Override
	public TabIdentifier getTabIdentifier() {
		return TabIdentifier.TAB_CHAT;
	}

	@Override
	public void clearOldAccountUI() {
		// 主线程调用，清理旧帐号的界面显示，最近联系人界面不需要处理
	}

	@Override
	public void loadDataToMemory() {
		// 后台线程调用
		RecentContactRecords.INSTANCE
				.loadFromDB(ChatConst.RECENT_CONTACT_MAX_ITEM_COUNTS);
	}

	@Override
	public void refreshWhenSwitchUser() {
		// 主线程调用
		setTitleText();
		addContentFragment();
	}
	
	/**
	 * 顶部按钮点击事件监听
	 */
	private TitleBtnCallback mTitleBtnCallBack = new TitleBtnCallback() {

		@Override
		public void onBtnClick(int clickType) {
			if (CommonActivityTitle.ON_RIGHT_CLICK_CALL_BACK == clickType) {
//				addFriendsOrGroup();
				ChatEntry.INSTANCE.chatCallOtherModel_UI
						.gotoAddFriendActivity(RecentContactRecordActivity.this);
			}else{
                // 转发情况下才可以关闭
                if (!isNormalUse()) {
                    finish();
                }
            }
		}
	};
	
	/**
	 * 发起群聊/添加朋友
	 * 
	 * <br>
	 * Created 2014-5-15 下午1:43:14
	 * 
	 * @author : linsj
	 */
	private void addFriendsOrGroup() {
		if (mPopup == null) {
			AddFriendOrGroupAdapter adapter = new AddFriendOrGroupAdapter(this);

			mPopup = new CommonPopup(mvewPopupAnchor, adapter, new IOnOper() {
				@Override
				public void onAction(int iAction) {
					switch (iAction) {
					case AddFriendOrGroupAdapter.ACTION_CREATE_GROUP:
						ChatEntry.INSTANCE.chatCallOtherModel_UI
								.gotoAddGroupMemberActivity(
										RecentContactRecordActivity.this,
										StarAppConst.ADD_GROUP_MEMBER_CONST.ADD_MODE_CREATE);
						break;
					case AddFriendOrGroupAdapter.ACTION_ADD_FRIENDS:
						ChatEntry.INSTANCE.chatCallOtherModel_UI
								.gotoAddFriendActivity(RecentContactRecordActivity.this);
						break;
					default:
						break;
					}
				}
			});
		}
		mPopup.show(0, 0);
	}
}
